var canvas_box = $('.canvas_box');
var my_canvas = $('#myCanvas');

if (canvas_box.length) {

    var R = 26,
        CW = $('body').width(),
        CH = $(document).height() - 420,
        OffsetX = 30,
        OffsetY = 30,
        div_y = canvas_box.offset().top,
        div_x = canvas_box.offset().left;
//alert(div_x)
    var c = document.getElementById("myCanvas");
    var cxt = c.getContext("2d");
    var Re = [];

    function CaculateNinePointLotion(diffX, diffY) {

        for (var row = 0; row < 3; row++) {
            for (var col = 0; col < 3; col++) {
                var Point = {
                    X: (OffsetX + col * diffX + (col * 2 + 1) * R),
                    Y: (OffsetY + row * diffY + (row * 2 + 1) * R)
                };
                Re.push(Point);
            }
        }
        return Re;
    }

    var PointLocationArr = [];

    function load_canvas(a) {
        CW = document.body.offsetWidth;
        c.width = CW;
        c.height = CH;
        //alert(unlock)
        //两个圆之间的外距离 就是说两个圆心的距离去除两个半径
        var X = (CW - 2 * OffsetX - R * 2 * 3) / 2;
        var Y = (CH - 2 * OffsetY - R * 2 * 3) / 2;
        PointLocationArr = CaculateNinePointLotion(X, Y);
        InitEvent(c, cxt, a);
        //CW=2*offsetX+R*2*3+2*X
        Draw(cxt, PointLocationArr, [], null);
        //console.log(a)
    }

    function Draw(cxt, _PointLocationArr, _LinePointArr, touchPoint) {
        if (_LinePointArr.length > 0) {
            cxt.beginPath();
            for (var i = 0; i < _LinePointArr.length; i++) {
                var pointIndex = _LinePointArr[i];
                cxt.lineTo(_PointLocationArr[pointIndex].X, _PointLocationArr[pointIndex].Y);
            }
            cxt.lineWidth = 3;
            cxt.strokeStyle = "#000";
            cxt.stroke();
            cxt.closePath();
            if (touchPoint != null) {
                var lastPointIndex = _LinePointArr[_LinePointArr.length - 1];
                var lastPoint = _PointLocationArr[lastPointIndex];
                cxt.beginPath();
                cxt.moveTo(lastPoint.X, lastPoint.Y);
                cxt.lineTo(touchPoint.X, touchPoint.Y);
                cxt.stroke();
                cxt.closePath();
            }
        }
        for (var i = 0; i < _PointLocationArr.length; i++) {
            var Point = _PointLocationArr[i];
            if (_LinePointArr.indexOf(i) >= 0) {
                cxt.fillStyle = "#ccc";
                cxt.beginPath();
                cxt.arc(Point.X, Point.Y, R, 0, Math.PI * 2, true);
                cxt.closePath();
                cxt.fill();

                cxt.fillStyle = "#fff";
                cxt.beginPath();
                cxt.arc(Point.X, Point.Y, R - 3, 0, Math.PI * 2, true);
                cxt.closePath();
                cxt.fill();

                cxt.fillStyle = "#000";
                cxt.beginPath();
                cxt.arc(Point.X, Point.Y, R - 13, 0, Math.PI * 2, true);
                cxt.closePath();
                cxt.fill();
            } else {
                cxt.fillStyle = "#fff";
                cxt.beginPath();
                cxt.arc(Point.X, Point.Y, R, 0, Math.PI * 2, true);
                cxt.closePath();
                cxt.fill();

                cxt.fillStyle = "#fff";
                cxt.beginPath();
                cxt.arc(Point.X, Point.Y, R - 3, 0, Math.PI * 2, true);
                cxt.closePath();
                cxt.fill();

                cxt.fillStyle = "#ccc";
                cxt.beginPath();
                cxt.arc(Point.X, Point.Y, R - 13, 0, Math.PI * 2, true);
                cxt.closePath();
                cxt.fill();
            }
            //LinePoint.push(i + 1);
        }

    }

    function IsPointSelect(touches, LinePoint) {
        for (var i = 0; i < PointLocationArr.length; i++) {
            var currentPoint = PointLocationArr[i];
            var y_val = touches.pageY - div_y;
            var x_val = touches.pageX - div_x;
            var xdiff = Math.abs(currentPoint.X - x_val);
            var ydiff = Math.abs(currentPoint.Y - y_val);
            var dir = Math.pow((xdiff * xdiff + ydiff * ydiff), 0.5);
            //alert(x_val+','+div_x)
            if (dir < R) {
                if (LinePoint.indexOf(i) < 0) {
                    LinePoint.push(i);
                }
                break;
            }
        }
    }

    var LinePoint = [];
    var confirmpwd = [];
    var puts = [];

    function InitEvent(canvasContainer, cxt, a) {

        canvasContainer.addEventListener("touchstart", function (e) {
            IsPointSelect(e.touches[0], LinePoint);
            console.log(e)
        }, false);
        canvasContainer.addEventListener("touchmove", function (e) {
            e.preventDefault();
            var touches = e.touches[0];
            IsPointSelect(touches, LinePoint);
            cxt.clearRect(0, 0, CW, CH);
            Draw(cxt, PointLocationArr, LinePoint, {X: touches.pageX - div_x, Y: touches.pageY - div_y});
        }, false);
        canvasContainer.addEventListener("touchend", function (e) {
            if (a === 1) {
                checkunlockpwd(LinePoint.toString());
                return false;
            } else if (a === 2) {
                if (LinePoint.length < 4) {
                    $('.tips').text('请至少连接4个点');
                    cxt.clearRect(0, 0, CW, CH); //清空画布
                    LinePoint = [];
                    Draw(cxt, PointLocationArr, LinePoint, null);
                    return false;
                } else {
                    settingunlockpwd()
                }
            }
        }, false);

        my_canvas.on('mousedown', function (e) {
            e = e || window.event;
            IsPointSelect(e, LinePoint);
            my_canvas.on('mousemove', function (e) {
                var touches
                touches = e;
                IsPointSelect(touches, LinePoint);
                cxt.clearRect(0, 0, CW, CH);
                Draw(cxt, PointLocationArr, LinePoint, {X: touches.pageX - div_x, Y: touches.pageY - div_y});
            })
            my_canvas.on('mouseup', function (e) {
                my_canvas.unbind('mousemove')
                if (a === 1) {
                    checkunlockpwd(LinePoint.toString());
                    return false;
                } else if (a === 2) {
                    if (LinePoint.length < 4) {
                        $('.tips').text('请至少连接4个点');
                        cxt.clearRect(0, 0, CW, CH); //清空画布
                        LinePoint = [];
                        Draw(cxt, PointLocationArr, LinePoint, null);
                        return false;
                    } else {
                        settingunlockpwd()
                    }
                }
            });
        });


        function init() {
            cxt.clearRect(0, 0, CW, CH); //清空画布
            LinePoint = [];
            Draw(cxt, PointLocationArr, LinePoint, null)
            //$('.tips').text('')
        }

        function checkunlockpwd(pwd) {
            Fast.api.ajax({
                url: 'index/check_point',
                data: {point: pwd}
            }, function (data, ret) {
                // Layer.msg(ret.msg);
                $('.tips').text(ret.msg).css({color: '#4cd964'});
                setTimeout(function () {
                    location.href = ret.url ? ret.url : "/";
                }, 1000);
                return false;
            }, function (data, ret) {
                $('.tips').text(ret.msg); //"身份识别码错误，请重新输入"
                setTimeout(function () {
                    location.reload();
                }, 1000);
                return false;
            });
        }

        function settingunlockpwd() {
            if (puts.length <= 0) {
                puts = LinePoint;
                //window.localStorage.setItem('passwordxx', JSON.stringify(puts))
                //alert(puts)
                for (var i = 0; i < puts.length; i++) {
                    //alert(puts[i])
                    $('.mm_icon span').eq(puts[i]).addClass('active')
                }
                $('.tips').text("再次绘制解锁图案");
                init()
            } else if (confirmpwd.length <= 0) {
                confirmpwd = LinePoint;
                //alert(confirmpwd)
            }

            if (puts.length > 0 && confirmpwd.length > 0) {
                if (comparearr(puts, confirmpwd)) {
                    //$('.tips').text("解锁图案绘制成功");
                    Fast.api.ajax({
                        url: 'index/save_point',
                        data: {new_point: confirmpwd.toString()}
                    }, function (data, ret) {
                        setTimeout(function () {
                            location.href = ret.url ? ret.url : "/";
                        }, 1000);
                        Layer.msg(ret.msg);
                        return false;
                    }, function (data, ret) {
                        $('.tips').text(ret.msg); //"身份识别码错误，请重新输入"
                        init();
                        return false;
                    });
                    init();
                } else {
                    $('.tips').text("两次绘制的解锁图案不一致");
                    init();
                    confirmpwd = [];
                }
            }
        }

        function comparearr(arr1, arr2) {
            //alert(arr1.tostring())
            //alert(arr1+','+arr2)
            //console.log(arr1.toString()===arr1.toString())
            return arr1.toString() === arr2.toString();
        }
    }

}